package com.quanyan.stadium.service.gameEvent.impl;

import com.google.common.collect.Lists;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.entity.RespClubPlainInfo;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.common.vo.Image;
import com.quanyan.stadium.api.req.ReqChallenge;
import com.quanyan.stadium.api.req.ReqCreateArrangeLiveGameEvent;
import com.quanyan.stadium.api.resp.v2.*;
import com.quanyan.stadium.biz.BizGameSystemDao;
import com.quanyan.stadium.component.pushMsg.MsgPush;
import com.quanyan.stadium.constants.GameConstants;
import com.quanyan.stadium.entity.*;
import com.quanyan.stadium.entity.vo.*;
import com.quanyan.stadium.enums.*;
import com.quanyan.stadium.service.commonComponent.BaseService;
import com.quanyan.stadium.service.commonComponent.OfficialGameCache;
import com.quanyan.stadium.service.gameEvent.LiveArrangeGameEventService;
import com.quanyan.stadium.service.gameRules.GameRoundService;
import com.quanyan.stadium.service.gameRules.GameScheduleService;
import com.quanyan.stadium.service.gameSign.GameSignUpService;
import com.quanyan.stadium.transfer.GameConfigTransfer;
import com.quanyan.stadium.utils.GameUtils;
import com.quanyan.stadium.utils.StringUtils;
import com.quanyan.user.response.RespUserInfoDetail;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;


/**
 * Created by lenovo on 2017/1/5.
 */
@Service
public class LiveArrangeGameEventServiceImpl implements LiveArrangeGameEventService {

    @Autowired
    private BaseService baseService;

    @Autowired
    private BizGameSystemDao bizGameSystemDao;

    @Autowired
    private GameRoundService gameRoundService;

    @Autowired
    private GameSignUpService gameSignUpService;

    @Autowired
    private OfficialGameCache officialGameCache;

    @Autowired
    private GameScheduleService gameScheduleService;
    @Autowired
    private GameConfigTransfer gameEventTransfer;

    @Value("${share.server.name}")
    private String shareServerName;

    private static final Logger logger = LoggerFactory.getLogger(LiveArrangeGameEventServiceImpl.class);

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public GameEvent createGameEvent(Integer uid, ReqCreateArrangeLiveGameEvent req) throws Exception {
        /**
         * 创建赛事
         */
        APIResponse<TbGameEvent> result = this.createGameEventTemp(uid, req);
        if(result.getErrcode() ==  ApiResponseEnum.FAIL.getId()){
            throw new BizException(null, result.getErrmsg());
        }

        TbGameEvent tbGameEvent =  result.getData();
        if (null == tbGameEvent){
            logger.error("赛事创建失败");
            throw new BizException(null, "赛事创建失败");
        }

        /**
         * 代报名
         */
        List<List<Integer>> uids = req.getUids();
        Integer isDouble = req.getIsDouble();
        if(uids.size() > 0){
            /**
             *双打报名条件检测
             */
            if(isDouble.intValue() == 1){
                for (List<Integer> singleId : uids){
                    if(singleId.size() != 2){
                        logger.error("双打的搭档人数必须为2，您传入的参赛人员是："+req.getUids().toString());
                        throw new BizException(null, "双打的搭档人数必须为2");
                    }
                }
            }

            APIResponse response = gameSignUpService.insertTeam(tbGameEvent.getId(),req.getUids(),req.getIsDouble());
            if(response.getErrcode() == ApiResponseEnum.FAIL.getId()){
                logger.error("参赛人员添加失败！参赛人员："+req.getUids().toString()+"出错！");
                throw new BizException(null, "参赛人员添加过程中出现错误");
            }
        }

        /**
         * 生成轮次
         */
        List<GameRound> gameRoundList = new ArrayList<>();
        if(null != tbGameEvent) {
            gameRoundList = gameRoundService.createGameRound(tbGameEvent);
            if(null == gameRoundList){
                logger.error("轮次创建失败，请确认参数是否正确！赛事id：" + tbGameEvent.getId());
                throw new BizException(null, "轮次创建失败");
            }
        }

        /**
         * 生成对战表
         */
        if(null != gameRoundList && gameRoundList.size() > 0){
            ReqChallenge reqChallenge = new ReqChallenge();
            reqChallenge.setGameEventId(tbGameEvent.getId());
            reqChallenge.setGameRoundId(gameRoundList.get(0).getId());
            reqChallenge.setIsArrange((byte)0);
            try {
                gameRoundService.generateCompListV2(reqChallenge);
            }catch (Exception e){
                logger.error("生产对战表失败！赛事id："+tbGameEvent.getId()+";轮次：" + gameRoundList.get(0).getId(),e);
                throw new BizException(null, "生产对战表失败");
            }
        }
        GameEvent event = new GameEvent();
        event.setId(tbGameEvent.getId());
        event.setName(tbGameEvent.getName());
        return event;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public APIResponse<Integer> createGameEventRound(Integer uid, ReqCreateArrangeLiveGameEvent req) throws Exception {

        TbGameEvent tbGameEvent =  bizGameSystemDao.selectTbGameEvent(req.getGameId());
        List<List<Integer>> uids = req.getUids();
        Integer isDouble = req.getIsDouble();
        if(uids.size() > 0){
            /**
             *双打报名条件检测
             */
            if(isDouble.intValue() == 1){
                for (List<Integer> singleId : uids){
                    if(singleId.size() != 2){
                        logger.error("双打的搭档人数必须为2，您传入的参赛人员是："+req.getUids().toString());
                        return APIResponse.returnFail("双打的搭档人数必须为2");
                    }
                }
            }

            APIResponse response = gameSignUpService.insertTeam(tbGameEvent.getId(),req.getUids(),req.getIsDouble());
            if(response.getErrcode() == ApiResponseEnum.FAIL.getId()){
                logger.error("参赛人员添加失败！参赛人员："+req.getUids().toString()+"出错！");
                return APIResponse.returnFail("参赛人员添加过程中出现错误");
            }
        }

        /**
         * 生成轮次
         */
        List<GameRound> gameRoundList = new ArrayList<>();
        if(null != tbGameEvent) {
            gameRoundList = gameRoundService.createGameRound(tbGameEvent);
            if(null == gameRoundList){
                logger.error("轮次创建失败，请确认参数是否正确！赛事id：" + tbGameEvent.getId());
                return APIResponse.returnFail("轮次创建失败");
            }
        }

        /**
         * 生成对战表
         */
        if(null != gameRoundList && gameRoundList.size() > 0){
            ReqChallenge reqChallenge = new ReqChallenge();
            reqChallenge.setGameEventId(tbGameEvent.getId());
            reqChallenge.setGameRoundId(gameRoundList.get(0).getId());
            reqChallenge.setIsArrange((byte)0);
            try {
                gameRoundService.generateCompListV2(reqChallenge);
            }catch (Exception e){
                logger.error("生产对战表失败！赛事id："+tbGameEvent.getId()+";轮次：" + gameRoundList.get(0).getId(),e);
                return APIResponse.returnFail("生产对战表失败！");
            }
        }
        return APIResponse.returnSuccess(tbGameEvent.getId());
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void intiGameEventRound(Integer uid, ReqCreateArrangeLiveGameEvent req) throws Exception {
        TbGameEvent tbGameEvent =  bizGameSystemDao.selectTbGameEvent(req.getGameId());
        if (null == tbGameEvent) {
            throw new BizException(null, "赛事不存在");
        }
        if (tbGameEvent.getSignEndTime().after(new Date())) {
            throw new BizException(null, "报名还未截止,无法开始编辑搭档");
        }
        if (tbGameEvent.getCurrentRoundId() > 0) {
            throw new BizException(null, "比赛已处于进行中,无法重新编辑搭档");
        }
        if (tbGameEvent.getCurrentRoundId() == -1) {
            throw new BizException(null, "比赛已结束,无法开始编辑搭档");
        }
        List<Integer> clubUids = baseService.getManageByClubId(tbGameEvent.getClubId());
        if (CollectionUtils.isNotEmpty(clubUids)) {
            if (!clubUids.contains(uid)) {
                throw new BizException(null, "只有俱乐部管理员才能编辑搭档");
            }
        }

        List<List<Integer>> uids = req.getUids();
        Integer isDouble = req.getIsDouble();
        if(uids.size() > 0){
            /**
             *双打报名条件检测
             */
            if(isDouble.intValue() == 1){
                for (List<Integer> singleId : uids){
                    if(singleId.size() != 2){
                        logger.error("双打的搭档人数必须为2，您传入的参赛人员是："+req.getUids().toString());
                        throw new BizException(null, "双打的搭档人数必须为2");
                    }
                }
            }
            gameSignUpService.updateDoubleTeam(tbGameEvent.getId(),req.getUids());
        }

        /**
         * 生成轮次
         */
        List<GameRound> gameRoundList = new ArrayList<>();
        if(null != tbGameEvent) {
            gameRoundList = gameRoundService.createGameRound(tbGameEvent);
            if(null == gameRoundList){
                logger.error("轮次创建失败，请确认参数是否正确！赛事id：" + tbGameEvent.getId());
                throw new BizException(null, "轮次创建失败");
            }
        }

        /**
         * 生成对战表
         */
        if(null != gameRoundList && gameRoundList.size() > 0){
            ReqChallenge reqChallenge = new ReqChallenge();
            reqChallenge.setGameEventId(tbGameEvent.getId());
            reqChallenge.setGameRoundId(gameRoundList.get(0).getId());
            reqChallenge.setIsArrange((byte)0);
            try {
                gameRoundService.generateCompListV2(reqChallenge);
            }catch (Exception e){
                logger.error("生产对战表失败！赛事id："+tbGameEvent.getId()+";轮次：" + gameRoundList.get(0).getId(),e);
                throw new BizException(null, "生产对战表失败！");
            }
        }
    }


    @Override
    public RespUserFLScoreMsg userFLScoreMsg(Integer gameEventId, Integer uid) {
        RespUserFLScoreMsg result = new RespUserFLScoreMsg();
        Map<Integer, Integer> gameScheduleFLScore = new HashMap<>();
        List<RespGameRound> respGameRoundV2s = new ArrayList<>();
        RespUserInfoDetail userInfoDetail = baseService.queryUserMsg(uid);
        if (null == userInfoDetail || userInfoDetail.getUid() <= 0) {
            logger.error("无法获取用户信息,错误原因:{}");
            return result;
        }
        result.setNickName(userInfoDetail.getNickName());
        result.setIcon(userInfoDetail.getIcon());
        List<TbUserGameSchedule> userGameSchedules = bizGameSystemDao.queryTbUserGameScheduleByUid(gameEventId, uid);
        if (CollectionUtils.isNotEmpty(userGameSchedules)) {
            List<Integer> ids = new ArrayList<>();
            for (TbUserGameSchedule gameSchedule : userGameSchedules) {
                ids.add(gameSchedule.getGameScheduleId());
                GameSchedule gameScheduleTemp = null;
                try {
                    gameScheduleTemp = officialGameCache.getGameSchedule(gameSchedule.getGameScheduleId(), GameConstants.TEAM_TYPE_PERSON);
                }  catch (Exception e) {
                    logger.error("获取缓存中的赛程id:{}出错", gameSchedule.getGameScheduleId());
                }
                RespGameSchedule v2 = new RespGameSchedule();
                try {
                    BeanUtils.copyProperties(v2, gameScheduleTemp);
                } catch (Exception e) {
                    logger.error("GameSchedule对象转化为RespGameScheduleV2失败,原因:{}", e);
                    e.printStackTrace();
                }
                List<RespGameSchedule> gameScheduleV2s = new ArrayList<>();
                gameScheduleV2s.add(v2);

                RespGameRound respGameRoundV2 = new RespGameRound();
                respGameRoundV2.setId(gameScheduleTemp.getRoundId());
                respGameRoundV2.setRoundType(respGameRoundV2s.size());
                respGameRoundV2.setGameScheduleV2s(gameScheduleV2s);
                respGameRoundV2s.add(respGameRoundV2);
                result.setRespGameRoundV2List(respGameRoundV2s);
            }
            List<TbUserFLScore> uMsg = bizGameSystemDao.queryTbUserFLScoreByUid(ids, uid);
            for (TbUserFLScore userFLScore : uMsg) {
                gameScheduleFLScore.put(userFLScore.getGameScheduleId(), (int) Math.round(userFLScore.getIncrScore()));
            }
            result.setGameScheduleFLScore(gameScheduleFLScore);
        }
        return result;
    }

    @Override
    public List<RespGameRound> liveGameSchedule(Integer gameEventId) {
        List<RespGameRound> respGameRoundV2s = new ArrayList<>();
        List<TbGameRound> tbGameRounds = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
        if (CollectionUtils.isNotEmpty(tbGameRounds)) {
            for (TbGameRound tbGameRound : tbGameRounds) {
                RespGameRound respGameRoundV2 = new RespGameRound();
                respGameRoundV2.setId(tbGameRound.getId());
                respGameRoundV2.setRoundType(respGameRoundV2s.size());
                List<TbGameSchedule> tbGameSchedules = bizGameSystemDao.selectTbGameScheduleByGameRoundId(tbGameRound.getId(), 0, GameConstants.GAME_SCHEDULE_NUM);
                if (CollectionUtils.isNotEmpty(tbGameSchedules)) {
                    List<RespGameSchedule> v2s = new ArrayList<>();
                    for (TbGameSchedule schedule : tbGameSchedules) {
                        RespGameSchedule v2 = new RespGameSchedule();
                        GameSchedule gameScheduleTemp = null;
                        try {
                            gameScheduleTemp = officialGameCache.getGameSchedule(schedule.getId(), GameConstants.TEAM_TYPE_PERSON);
                            BeanUtils.copyProperties(v2, gameScheduleTemp);
                        } catch (Exception e) {
                            logger.error("GameSchedule对象转化为RespGameScheduleV2失败/获取当前赛程:"+schedule.getId()+"失败,原因:{}", e);
                            e.printStackTrace();
                        }
                        v2s.add(v2);
                    }
                    respGameRoundV2.setGameScheduleV2s(v2s);
                }
                respGameRoundV2s.add(respGameRoundV2);
            }
        }
        return respGameRoundV2s;
    }

    @Override
    public RespGameDetail liveGameEventDetailV2(Integer gameEventId, Integer uid) {
        RespGameDetail detail = new RespGameDetail();
        detail.setUserRole(GameConstants.IS_NOT_DELETE);
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        if (null == gameEvent || gameEvent.getId() < 1)
            return detail;
        List<Integer> uIds = baseService.getManageByClubId(gameEvent.getClubId());
        if (uIds.contains(uid)) {
            detail.setUserRole(GameConstants.IS_DELETE);
        }

        logger.info("LiveArrangeGameEventServiceImpl.liveGameEventDetailV2中数据,用户权限userRole:{}", detail.getUserRole());
        detail.setId(gameEvent.getId());
        detail.setCurrentGameRoundId(gameEvent.getCurrentRoundId());
        detail.setName(gameEvent.getName());
        detail.setCreateTime(gameEvent.getCreateTime().getTime());
        detail.setCurrentNum(gameEvent.getTeamLimitNum() - gameEvent.getInventoryLevel());
        detail.setGameCategory(gameEventTransfer.getGameCategoryById(gameEvent.getGameCategoryType().intValue()));
        detail.setGameSystem(gameEventTransfer.getGameSystemById(gameEvent.getGameSystemType().intValue()));
        if (null != gameEvent.getCurrentRoundId()) {
            detail.setGameCategory(gameEventTransfer.getGameCategoryById(gameEvent.getGameCategoryType().intValue()));
            detail.setGameSystem(gameEventTransfer.getGameSystemById(gameEvent.getGameSystemType().intValue()));
            if (null != gameEvent.getCurrentRoundId()) {
                List<TbGameRound> gameRounds = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
                List<RespGameRound> respGameRoundV2s = new ArrayList<>();
                RespGameRound respGameRoundV2 = new RespGameRound();
                respGameRoundV2.setId(gameEvent.getCurrentRoundId());
                respGameRoundV2.setRoundType(gameEvent.getCurrentRoundId() - gameRounds.get(0).getId());
                List<TbGameSchedule> tbGameSchedules = bizGameSystemDao.selectTbGameScheduleByGameRoundId(gameEvent.getCurrentRoundId(), 0, GameConstants.GAME_SCHEDULE_NUM);
                if (CollectionUtils.isNotEmpty(tbGameSchedules)) {
                    List<RespGameSchedule> v2s = new ArrayList<>();
                    for (TbGameSchedule schedule : tbGameSchedules) {
                        RespGameSchedule v2 = new RespGameSchedule();
                        GameSchedule gameScheduleTemp = null;
                        try {
                            gameScheduleTemp = officialGameCache.getGameSchedule(schedule.getId(), GameConstants.TEAM_TYPE_PERSON);
                            BeanUtils.copyProperties(v2, gameScheduleTemp);
                        } catch (Exception e) {
                            logger.error("GameSchedule对象转化为RespGameScheduleV2失败/获取当前赛程:" + schedule.getId() + "失败,原因:{}", e);
                            e.printStackTrace();
                        }
                        if (detail.getUserRole().intValue() == GameConstants.IS_DELETE.intValue()) {
                            v2.setRecordAuth(GameConstants.IS_DELETE);
                        }else {
                            if (uid > 0) {
                                Set<User> tempUser = new HashSet<>();
                                if (null!=gameScheduleTemp.getHomeGameTeam() && com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(gameScheduleTemp.getHomeGameTeam().getUserList())) {
                                    tempUser.addAll(gameScheduleTemp.getHomeGameTeam().getUserList());
                                }
                                if (null!=gameScheduleTemp.getAwayGameTeam() && com.alibaba.dubbo.common.utils.CollectionUtils.isNotEmpty(gameScheduleTemp.getAwayGameTeam().getUserList())) {
                                    tempUser.addAll(gameScheduleTemp.getAwayGameTeam().getUserList());
                                }
                                if (CollectionUtils.isNotEmpty(tempUser)) {
                                    for (User u : tempUser) {
                                        if (null!=u.getUid() && u.getUid().intValue() == uid.intValue()) {
                                            v2.setRecordAuth(GameConstants.IS_DELETE);
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                        v2s.add(v2);
                    }
                    respGameRoundV2.setGameScheduleV2s(v2s);
                    respGameRoundV2s.add(respGameRoundV2);
                }
                detail.setRoundNum(gameRounds.size());
                detail.setRespGameRoundV2s(respGameRoundV2s);
            }
        }
        detail.setRankList(getUserScoreRank(gameEventId).getRankList());
        return detail;
    }

    @Override
    public List<RespGameSchedule> openNextGameRoundV2(Integer gameEventId, Integer gameRoundId, Integer uid) throws Exception {
        List<RespGameSchedule> result = new ArrayList<>();
        ReqChallenge reqChallenge = new ReqChallenge();
        reqChallenge.setGameEventId(gameEventId);
        reqChallenge.setIsArrange(GameConstants.IS_NOT_DELETE);
        List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventId(reqChallenge.getGameEventId());
        int waitGenerateGameRoundId = -1;
        for (int i=0;i<tbGameRoundList.size();i++) {
            if (tbGameRoundList.get(i).getId().intValue() == gameRoundId.intValue()) {
                if ((i+1) < tbGameRoundList.size()){
                    waitGenerateGameRoundId = tbGameRoundList.get(i+1).getId();
                    break;
                }
            }
        }
        reqChallenge.setGameRoundId(waitGenerateGameRoundId);
        Map<Integer, List<GameSchedule>> params = gameRoundService.generateCompListV2(reqChallenge);
        List<GameSchedule> temp = params.get(waitGenerateGameRoundId);
        for (GameSchedule schedule : temp) {
            RespGameSchedule re = new RespGameSchedule();
            re.setGameRoundId(waitGenerateGameRoundId);
            re.setId(schedule.getId());
            re.setHomeGameTeam(schedule.getHomeGameTeam());
            re.setAwayGameTeam(schedule.getAwayGameTeam());
            re.setIsWin(schedule.getIsWin());
            re.setRecordStatus(schedule.getRecordStatus());
            re.setScore(schedule.getScore());
            result.add(re);
        }
        return result;
    }

    @Override
    public RespGameUserRank getUserScoreRank(Integer gameEventId) {
        RespGameUserRank result = new RespGameUserRank();
        List<GameTeam> temp = new ArrayList<>();
        TbGameEvent gameEvent = bizGameSystemDao.selectTbGameEvent(gameEventId);
        if (null == gameEvent || gameEvent.getId()<1) {
            throw new BizException(null, "赛事不存在");
        }
        result.setId(gameEvent.getId());
        result.setName(gameEvent.getName());

        //分享信息
        TbGameCommonParameter tbGameCommonParameter = baseService.queryTbGameCommonParameter(GameConstants.STADIUM_DEFAULT_GROUP_BASE_CONFIG_KEY,
                MsgPush.GAME_SCENE_EVENT_RANK_LIST_SHARE_URL);
        result.setShareUrl(shareServerName+tbGameCommonParameter.getParameterValue());

        if (gameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId()) {
            int lastRoundId = gameEvent.getCurrentRoundId();
            boolean falg = false;
            if (gameEvent.getCurrentRoundId() == -1) {
                List<TbGameRound> tbGameRoundList = bizGameSystemDao.selectTbGameRoundByGameEventId(gameEventId);
                lastRoundId = tbGameRoundList.get(tbGameRoundList.size()-1).getId();
                falg = true;
            }

            List<TbGameSchedule> tbGameSchedules = bizGameSystemDao.selectTbGameScheduleByGameRoundId(lastRoundId, 0, GameConstants.GAME_SCHEDULE_NUM);
            if (CollectionUtils.isNotEmpty(tbGameSchedules) && gameEvent.getGameSystemType().intValue() == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId()) {
                TbGameSchedule schedule = tbGameSchedules.get(0);

                // 抢签赛特殊处理 begin
                String teamList = schedule.getTeamListIndex();
                if (falg && StringUtils.isNotEmpty(schedule.getLastTeamListIndex())) {
                    teamList = schedule.getLastTeamListIndex();
                }
                // end
                List<TbGameEventTeam> teams = bizGameSystemDao.selectTbGameEventTeamByIds(new Gson().<List<Integer>>fromJson(teamList, new TypeToken<List<Integer>>() {
                }.getType()));
                try {
                    temp = gameScheduleService.tbGameTeamTransferGameTeam(gameEvent, teams, GameConstants.TEAM_TYPE_PERSON);
                } catch (Exception e) {
                    logger.error("tbGameEventTeam转化出错GameTeam,原因:{}", e);
                }
            }
        } else {
            if(gameEvent.getCurrentRoundId().intValue() == -1) {
                List<TbGameEventScore> tbGameEventScores = bizGameSystemDao.queryTbGameEventScoreList(gameEventId);
                if (CollectionUtils.isNotEmpty(tbGameEventScores)) {
                    try {
                        temp = gameScheduleService.tbGameTeamTransferGameTeamV2(gameEvent, tbGameEventScores, GameConstants.TEAM_TYPE_PERSON);
                    } catch (Exception e) {
                        logger.error("tbGameEventScore转化出错GameTeam,原因:{}", e);
                    }
                    Collections.sort(temp, new Comparator<GameTeam>() {   //排名
                        public int compare(GameTeam o1, GameTeam o2) {
                            return o1.getRank().compareTo(o2.getRank());
                        }
                    });
                }
            }
        }

        result.setRankList(temp);
        return result;
    }


    /**
     * 创建赛事
     */
    protected APIResponse<TbGameEvent> createGameEventTemp(Integer uid, ReqCreateArrangeLiveGameEvent req){

        /**
         * 赛制与玩法对应关系判断
         */
        byte gameSystemType = req.getGameSystemType();
        byte gamecategoryType =  req.getGameCategoryType();
        if(gameSystemType == GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getId()){
            if(gamecategoryType == GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_V8.getId()){
                if(req.getUids().size() != 8){
                    logger.error(GameSystemConfigEnum.CONFIG_GAME_TYPE_EIGHT_RULE.getName()+"——8人制人数必须为8人");
                    return APIResponse.returnFail("您传入的赛制类型没有找到玩法类型");
                }
            }else{
                logger.error("您传入的赛制类型为:"+GameSystemConfigEnum.CONFIG_GAME_TYPE_UNSET_RULE.getName()+"，请确认传入玩法类型的参数是否正确！");
                return APIResponse.returnFail("您传入的赛制类型没有找到玩法类型");
            }
        }else if(gameSystemType == GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS.getId() ){
            if(req.getUids().size() < 2){
                return APIResponse.returnFail("等位制报名人数至少为2才能组成比赛");
            }else if(req.getUids().size() > 1024){
                return APIResponse.returnFail("超出等位制报名人数限制");
            }else{
                if(gamecategoryType != GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_ONLY.getId()
                        && gamecategoryType != GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE.getId()){
                    logger.error("您传入的赛制类型为:"+GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS.getName()+"，请确认传入玩法类型的参数是否正确！");
                    return APIResponse.returnFail("您传入的赛制类型没有找到玩法类型");
                }
                if(gamecategoryType == GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE.getId()){
                    if(req.getUids().size() < 2){
                        logger.error(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS.getName()+GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE.getName()+"最少要两支队伍");
                        return APIResponse.returnFail(GameSystemConfigEnum.CONFIG_GAME_TYPE_SWISS.getName()+GameCategoryConfigEnum.CONFIG_GAME_CATEGORY_NOT_KNOW_DOUBLE.getName()+"最少要两支队伍");
                    }
                }
            }
        }else{
            logger.error("赛制类型参数有误，请确认传入参数！");
            return APIResponse.returnFail("赛制类型参数有误，请确认传入参数！");
        }
        try {
            List<Integer> uidList = Lists.newArrayList();
            if(req.getUids()!=null && req.getUids().size()>0) {
                for (List<Integer> uList : req.getUids()) {
                    if (uList != null && uList.size() > 0) {
                        for(Integer i : uList){
                            uidList.add(i);
                        }
                    }
                }
            }
            gameSignUpService.updateTbRecentUser(uid,uidList);
            gameSignUpService.updateUserSignCount(uidList,req.getCategoryId());
        }catch (Exception e){
            logger.error("更新历史代报名失败！");
        }
        /**
         * 创建者权限控制
         */
        List<Integer> uids = baseService.getManageByClubId(req.getClubId());
        if (CollectionUtils.isEmpty(uids) || !uids.contains(uid)) {
            logger.error("只有该俱乐部管理员和主席才能现场编排");
            return APIResponse.returnFail("只有该俱乐部管理员和主席才能现场编排");
        }

        /**
         * 为现场编排配置官方信息
         */
        Gson gson =new Gson();
        RespClubPlainInfo club = baseService.queryClubMsg(req.getClubId());
        if (null == club || club.getClubId() < 1) {
            logger.error("该俱乐部不存在");
            return APIResponse.returnFail("该俱乐部不存在");
        }
        int cityId = club.getCityId();
        int distId = club.getDistinctId();

        TbGameEvent tbGameEvent = new TbGameEvent();
        tbGameEvent.setCityId(cityId);
        tbGameEvent.setDistrictId(distId);
        tbGameEvent.setName(req.getGameEventName());
        tbGameEvent.setCategoryId(req.getCategoryId());
        tbGameEvent.setType(GameConstants.CLUB_CREATE);
        tbGameEvent.setUid(uid);
        tbGameEvent.setClubId(req.getClubId());
        tbGameEvent.setGameSystemType(req.getGameSystemType());
        tbGameEvent.setGameCategoryType(req.getGameCategoryType());
        tbGameEvent.setGameEventType((byte) GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_SCENE.getId());

        tbGameEvent.setIsVisible((byte) 1);
        tbGameEvent.setGameTeamType(GameConstants.IS_NOT_DELETE);
        int teamNum = req.getUids().size();
        tbGameEvent.setTeamLimitNum(teamNum);
        tbGameEvent.setInventoryLevel(teamNum);
        tbGameEvent.setPayType((byte) PayTypeEnum.CONFIG_PAY_TYPE_FREE.getId());
        tbGameEvent.setPrice(new BigDecimal(0));
        tbGameEvent.setTeamGroupNum(0);
        tbGameEvent.setRankNum(0);

        /**
         * 将赛事相关时间设置为当前时间
         */
        Date currentTime = new Date();
        tbGameEvent.setSignStartTime(currentTime);
        tbGameEvent.setSignEndTime(currentTime);
        tbGameEvent.setStartTime(currentTime);
        tbGameEvent.setEndTime(DateUtils.addTime(currentTime, 24, DateUtils.TIME_TYPE_HOUR));

        MultiMedia multiMedia = new MultiMedia();
        Image image = new Image();
        image.setImageUrl(club.getLogo());
        List<TbGamePoster> posters = bizGameSystemDao.queryTbGamePosterList(req.getCategoryId());
        if (CollectionUtils.isNotEmpty(posters)) {
            image.setImageUrl(posters.get(new Random().nextInt(posters.size())).getUrl());
        }
        tbGameEvent.setManagerName(club.getClubName());
        multiMedia.setType(GameConstants.IS_NOT_DELETE);  //标识为图片
        multiMedia.setImage(image);
        tbGameEvent.setMultiMedia(gson.toJson(multiMedia));
        /**
         * 生产赛事编号
         */
        String gameCode = GameUtils.generateGameCode((byte) GameTypeConfigEnum.CONFIG_GAME_EVENT_TYPE_NGKC.getId(), req.getCategoryId(), 0, req.getGameSystemType().byteValue());
        tbGameEvent.setGameNumber(gameCode);
        tbGameEvent.setName(req.getGameEventName());
        tbGameEvent = bizGameSystemDao.insertTbGameEvent(tbGameEvent);
        if (null == tbGameEvent.getId())
            new BizException(null, ErrorEnum.ERROR_DB.getLabel());
        logger.info("现场编排赛事成功.俱乐部ID{}.赛事ID{}",req.getClubId(),tbGameEvent.getId());

        return APIResponse.returnSuccess(tbGameEvent);
    }


}
